package com.leal.client;

import org.apache.http.HttpHost;
import org.apache.log4j.Logger;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;


import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * @Classname bigdata
 * @Description 尝试使用hive level api 连接
 * @Date 2024/8/8 16:05
 * @Created by leal
 */
public class ESClient {

    public static Logger logger = Logger.getLogger(ES6Client.class);

    public static RestHighLevelClient getClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http"),
                        new HttpHost("127.0.0.1", 9300, "http")
                )
        );
    }

    public static void close(RestHighLevelClient client) {
        try {
            client.close();
        } catch (Exception e) {
            logger.error("关闭ES客户端出错", e);
        }
    }

    //创建索引
    public static boolean createIndex(RestHighLevelClient client, String indexName) throws IOException {

        // 创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(indexName);

        // 可选: 添加映射
        request.mapping("properties",
                jsonBuilder()
                        .startObject()
                        .startObject("properties")
                        .startObject("user")
                        .field("type", "text")
                        .endObject()
                        .startObject("postDate")
                        .field("type", "date")
                        .endObject()
                        .startObject("message")
                        .field("type", "text")
                        .endObject()
                        .endObject()
                        .endObject()
                , XContentType.JSON
        );

        return false;
    }
}
